# -*- encoding: utf-8 -*-
"""
@File    :   mockapi.py    
@lastModifyTime    :   2021-11-19

程序功能，模拟api给前端返回数据，一个JSON文件即一个API接口

1、新增一个模拟接口，只需要创建一个JSON文件。
2、JSON文件名，以.进行分割，对应api的请求地址，
如：
api.employer.json 对应请求地址： /api/employer
api.Entrust.EntrustVideoList.json 对应请求地址：/api/Entrust/EntrustVideoList
3、JSON文件内容即模拟返回的请求结果
{
    "code": "0",
    "msg": "成功",
    "count": 1,
    "pageIndex": 1,
    "pageCount": 1,
    "data":[
        {
            "rownumber": 1,
            "id": "82660813-ff99-49c7-864c-c8e5e03f1497",
            "serialnum": "YNHX-YC-2020-0001",
            "category": "自有检测用车",
            "deptname": "运营中心", 
            "cardispatchertext": " 穆加强"    
        }
    ]
}

"""

from time import sleep
import sys
import json
from flask import Flask, request, jsonify
from flask.globals import g
from flask.signals import _signals
import hashlib
import os
from flask import make_response
from flask_cors import CORS

app = Flask(__name__)
CORS(app, resources=r'/*')  # 跨域相关
app.config['JSON_AS_ASCII'] = False
request_started = _signals.signal('request-started')
total = 0


# 读取JSON文件
def GetData(fileName):
    try:
        with open(fileName, "r", encoding="utf-8") as f:
            content = f.read()
        responseData = eval(content)
    except BaseException as e:
        responseData = {
            "code": "0",
            "msg": "没有找到data文件",
            "count": 0,
            "pageIndex": 0,
            "pageCount": 0,
            "data": ""
        }
    return responseData


# 接口请求系统信号（signal）绑定
def ImportData(sender, *args, **kwargs):
    pass


request_started.connect(ImportData)

# 动态创建API接口
autoScript = ""
currentDir = os.path.join(os.getcwd(), "responses")
fileLis = os.listdir(currentDir)
for file in fileLis:
    fileName = str(file)
    filePath = os.path.join(currentDir, fileName)
    if fileName.split(".")[-1].upper() != "JSON":
        continue
    urls = fileName.split(".")[:-1]
    url = "/".join(urls)
    autoScript += f"@app.route('/{url}', methods=['POST', 'GET'])\n"
    autoScript += f"def {urls[-1]}():\n"
    autoScript += f"    response = make_response(jsonify(GetData(r'{filePath}')))\n"
    autoScript += f"    response.headers['Access-Control-Allow-Origin'] = '*'\n"
    autoScript += f"    return response\n"

print(autoScript)
exec(autoScript)

if __name__ == '__main__':
    app.run(host='127.0.0.1', port=8123, debug=True)
